/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.saber.certificacao.ejbs.stateless;

import br.com.saber.certificacao.ejbs.stateless.interfaces.RolesBeanLocal;
import br.com.saber.certificacao.enums.Papeis;
import br.com.saber.certificacao.modelos.Roles;
import br.com.saber.certificacao.modelos.Usuario;
import java.util.Set;
import java.util.TreeSet;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
 *
 * @author gbvbahia
 */
@Stateless
public class RolesBean implements RolesBeanLocal {
    
   @PersistenceContext(name = "jdbc/saber")
    private EntityManager manager;

    @Override
    public Papeis getMaxRole(Set<Roles> roles) {
        Papeis toReturn = null;
        for (Roles role : roles) {
            if(toReturn == null){
                toReturn = role.getPapel();
                continue;
            }else if(toReturn.getLevel() < role.getPapel().getLevel()) {
                toReturn = role.getPapel();
                continue;
            }
        }
        return toReturn;
    }

    @Override
    public Set<Roles> getAllRoles() {
        Set<Roles> toReturn = null;
        Query q = manager.createNamedQuery("RolesBean.getAllRoles");
        toReturn = new TreeSet<Roles>(q.getResultList());
        return toReturn;
    }

    @Override
    public Roles getRoleByID(Long id) {
        try{
            return manager.find(Roles.class, id);
        }catch(NoResultException e){
            return null;
        }
    }

    /**
     * Retorna as roles que o usuário passado tem acesso a liberar
     * no cadastro de outro usuário
     * @param usuario
     * @return
     */
    @Override
    public Set<Roles> getRolesParaLiberar(Usuario usuario) {
        TreeSet<Roles> toReturn = new TreeSet<Roles>();
        for(Roles role: getAllRoles()){
            if(getMaxRole(usuario.getRoles()).equals(Papeis.ADMINISTRADOR)){
            toReturn.add(role);
            }else{
                if(getMaxRole(usuario.getRoles()).getLevel() > role.getPapel().getLevel()){
                    toReturn.add(role);
                }
            }
        }
        return toReturn;
    }

    @Override
    public Roles buscarRolePorPapel(Papeis papel) {
        for(Roles role : this.getAllRoles()){
            if(role.getPapel().equals(papel)){
                return role;
            }
        }
        return null;
    }

 
}
